<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <div style="height: 450px" v-if="!pageData.meshConfigsJson">
      <ProTable
        ref="tableRef"
        :columns="columns"
        :fetch-list-api="async () => ({ rows: formState.meshDeviceBeanList })"
        row-key="deviceName"
        hide-pagination
        hide-search
      >
        <template #operation="{ record }">
          <b-button
            @click="handleBind(record)"
            v-if="formState.protocolVersion == '2'"
            type="link"
            code="mesh:frequency"
          >
            对频
          </b-button>
          <b-button @click="deleteMesh(record)" type="link">移除</b-button>
        </template>
      </ProTable>
    </div>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="postWirelessConfigList"
      @refresh="refresh"
      :fastConfig="fastConfig"
      v-hasPermission="'mesh:edit'"
    />
    <FormModal :items="testItems">
      <template #verityCode="{ formState }">
        <Input v-model:value="formState.verityCode" placeholder="请输入验证码">
          <template #suffix>
            <Button
              @click="getCode"
              :disabled="codeTime != 0"
              type="link"
              style="margin: -5px"
              >{{ codeTime ? `${codeTime}s` : '获取验证码' }}</Button
            ></template
          >
        </Input>
      </template>
    </FormModal>
  </template>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef, watch } from 'vue';
import { Button, Input, Modal, Space, message } from 'ant-design-vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import {
  checkFrequency,
  checkVerityCode,
  deviceTest,
  getCheckCode,
  getRunningModeConfig,
  getWirelessConfigList,
  onlineDetection,
  postWirelessConfigList,
} from '@/api/device';
import FooterButtons from './FooterButtons.vue';

defineOptions({
  name: 'Mesh',
});

interface Props {
  pageData: any;
  readonly?: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(props.readonly ?? true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 7 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
  rules: any = [],
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
      ...rules,
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const radioOptions = [
  { value: 0, label: '关闭' },
  { value: 1, label: '开启' },
];
const frequencyListV1 = [
  { label: '401.00000', value: '401.00000' },
  { label: '410.02500', value: '410.02500' },
  { label: '415.02500', value: '415.02500' },
  { label: '420.02500', value: '420.02500' },
  { label: '430.02500', value: '430.02500' },
  { label: '435.02500', value: '435.02500' },
  { label: '440.02500', value: '440.02500' },
  { label: '450.02500', value: '450.02500' },
  { label: '455.02500', value: '455.02500' },
  { label: '460.02500', value: '460.02500' },
];
const frequencyListV2 = ref([]);
const runningMode = ref('');
const countdown = ref(0);
console.log(
  formState.value.protocolVersion,
  '----------------------------------',
);

const items = computed<ProFormProps['items']>(() =>
  props.pageData.meshConfigsJson
    ? [
        itemRender('无线组网'),
        itemObj('无线组网', 'radio', 'isOpenMesh', true, {
          options: radioOptions,
        }),
      ]
    : [
        itemRender('无线组网'),
        itemObj('无线组网频率', 'select', 'meshFrequency', true, {
          options:
            formState.value.protocolVersion > '1'
              ? frequencyListV2.value
              : frequencyListV1,
        }),
        itemObj('无线组网', 'radio', 'isOpenMesh', true, {
          options: radioOptions,
        }),
        // itemObj('通讯协议', 'select', 'protocolVersion', true, {
        //   options: [
        //     { value: '1', label: 'V1版本' },
        //     { value: '2', label: 'V2版本' },
        //   ],
        // }),
        {
          label: '',
          type: 'input',
          field: 'button',
          customRender() {
            return (
              <Space>
                <Button
                  onClick={getLogin}
                  disabled={
                    !readonly.value ||
                    countdown.value != 0 ||
                    (formState.value.meshDeviceBeanList?.length ?? 0) == 0
                  }
                  v-hasPermission='mesh:detection'
                >
                  {countdown.value ? `${countdown.value}s` : '检测'}
                </Button>
                {runningMode.value == '0' ? (
                  <Button
                    onClick={getTest}
                    disabled={!readonly.value}
                    v-hasPermission='mesh:test'
                  >
                    测试
                  </Button>
                ) : null}
                <Button onClick={addOnlineDetection}>添加设备</Button>
              </Space>
            );
          },
          hide(state) {
            return state.isOpenMesh != 1;
          },
        },
      ],
);

const getWirelessList = () => {
  getWirelessConfigList(props.pageData.code).then((res: any) => {
    formState.value = res.data;
    formState.value.code = props.pageData.code;
    formState.value.meshFrequency = parseFloat(res.data.meshFrequency).toFixed(
      5,
    );
    console.log(res.data.frequencyList, '----------------------------------');

    frequencyListV2.value = res.data.frequencyList
      ? res.data.frequencyList.split(',').map((item: string) => {
          return {
            label: item,
            value: item,
          };
        })
      : [];
    loaded.value = true;
  });
};

props.pageData.meshConfigsJson
  ? (() => {
      formState.value = JSON.parse(props.pageData.meshConfigsJson);
      loaded.value = true;
    })()
  : (async () => {
      const rm: any = await getRunningModeConfig(props.pageData.code);
      runningMode.value = rm.data.runningMode;
      getWirelessList();
    })();

const getLogin = () => {
  countdown.value = 60;
  onlineDetection(props.pageData.code).then((res: any) => {
    if (res.code == 200) {
      message.success(res.msg);
    }
  });
  let interval = setInterval(() => {
    countdown.value--;
    if (countdown.value == 0) {
      clearInterval(interval);
      setTimeout(() => {
        getWirelessList();
      }, 2000);
    }
  }, 1000);
};

const testItems = [itemObj('验证码', 'input', 'verityCode', true)];
const { FormModal, open } = useFormModal({
  size: 'mini',
  column: 1,
  formProps: { labelCol: { span: 6 } },
});
const getTest = () => {
  if (!formState.value.meshDeviceBeanList.length)
    return message.error('无设备!');
  open({
    title: '测试',
    defaultValue: {
      type: '1',
      code: props.pageData.code,
    },
    serviceApi: async (params: any): Promise<any> => {
      await checkVerityCode(params);
      message.success('验证码正确');
      await deviceTest(props.pageData.code);
      message.success('测试成功');
    },
  });
};

let codeTime = ref(0);
const getCode = async () => {
  codeTime.value = 60;
  await getCheckCode({ type: '1', code: props.pageData.code });
  let timer = setInterval(() => {
    codeTime.value--;
    if (codeTime.value == 0) {
      clearInterval(timer);
    }
  }, 1000);
};

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
  },
  ...(formState.value.protocolVersion == '2'
    ? [
        {
          title: '组网频率',
          dataIndex: 'frequency',
        },
      ]
    : []),
  {
    title: '是否在线',
    dataIndex: 'deviceStatus',
    width: 100,
    customRender({ record }) {
      return record.deviceStatus == 0
        ? '待校验'
        : record.deviceStatus == 1
          ? '已校验 在线'
          : '已校验 离线';
    },
  },
  {
    title: '最后效验时间',
    dataIndex: 'lastCheckTime',
  },
  ...(!readonly.value
    ? [
        {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
        },
      ]
    : []),
]);
const addOnlineDetection = () => {
  const items = [itemObj('设备名称', 'input', 'deviceName', true)];
  open({
    title: '添加设备',
    items,
    defaultValue: {
      deviceStatus: '0',
      lastCheckTime: '',
      frequency:
        formState.value.protocolVersion == '2' ? '409.00625' : '460.02500',
    },
    serviceApi: async (params: any): Promise<any> => {
      formState.value.meshDeviceBeanList.push(params);
    },
  });
};
const handleBind = (row: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: '是否进行设备对频?',
    onOk: async () => {
      row.code = props.pageData.code;
      const res = await checkFrequency(row);
      message.success(res.msg);
    },
  });
};
const deleteMesh = (row: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: '是否移除设备?',
    onOk: async () => {
      const rawArr = formState.value.meshDeviceBeanList;
      for (let i = rawArr.length - 1; i >= 0; i--) {
        if (rawArr[i].deviceName == row.deviceName) {
          rawArr.splice(i, 1);
        }
      }
      message.success('移除成功');
    },
  });
};

defineExpose({
  async save() {
    const data = await formRef.value.validate();
    props.pageData.meshConfigsJson = JSON.stringify(data);
  },
});
</script>
